
using UnityEngine;
using System;

/// <summary>
/// 登录模块管理类
/// 提供华为账号登录支持，包括标准登录流程和仅华为账号登录
/// </summary>
public class LoginManager: MonoBehaviour
{
    /// <summary>
    /// OpenHarmony JS对象，用于与原生登录模块交互
    /// </summary>
    public static OpenHarmonyJSObject m_HMSLoginManagerObj { get; private set; } = null;

    /// <summary>
    /// 登录回调事件，用于接收登录结果
    /// </summary>
    public static Action<string, string> HMSLoginManagerCallback = null;

    /// <summary>
    /// OpenHarmony JS回调对象
    /// </summary>
    private static OpenHarmonyJSCallback _hmsLoginManagerCallback;

    /// <summary>
    /// 处理来自OpenHarmony的登录回调
    /// </summary>
    /// <param name="args">回调参数，第一个参数为类型，第二个参数为数据</param>
    /// <returns>无返回值</returns>
    private static object HMSLoginCallback(params OpenHarmonyJSObject[] args)
    {
        Debug.Log("Hwlogin:HMSLoginCallback: " + args.Length);
        if (args.Length > 0)
        {
            Debug.Log("Hwlogin:HMSLoginCallback type: " + args[0].As<string>());
            Debug.Log("Hwlogin:HMSLoginCallback data: " + args[1].As<string>());
            HMSLoginManagerCallback?.Invoke(args[0].As<string>(), args[1].As<string>());
        }
        return null;
    }

    /// <summary>
    /// 标准登录流程（有官方账号登录）
    /// 初始化登录模块并开始登录流程
    /// </summary>
    /// <param name="callback">登录结果回调，参数为(类型, 数据)</param>
    public static void Login(Action<string, string> callback)
    {
        Debug.Log("Hwlogin:Init >>>>");
        _hmsLoginManagerCallback = new OpenHarmonyJSCallback(HMSLoginCallback);
        var loginManager = new OpenHarmonyJSClass("LoginManager");
        m_HMSLoginManagerObj = loginManager.CallStatic<OpenHarmonyJSObject>("GetInstance");
        Debug.Log($"Hwlogin:CreateHMSManager:HMSAdsManagerObj={m_HMSLoginManagerObj}");

        HMSLoginManagerCallback = callback;
        m_HMSLoginManagerObj.Call("Login", _hmsLoginManagerCallback); 
    }
    
    /// <summary>
    /// 仅使用华为账号登录
    /// 初始化登录模块并仅使用华为账号进行登录
    /// </summary>
    /// <param name="callback">登录结果回调，参数为(类型, 数据)</param>
    public static void LoginHwOnly(Action<string, string> callback)
    {
        Debug.Log("Hwlogin:Init >>>>");
        _hmsLoginManagerCallback = new OpenHarmonyJSCallback(HMSLoginCallback);
        var loginManager = new OpenHarmonyJSClass("LoginManager");
        m_HMSLoginManagerObj = loginManager.CallStatic<OpenHarmonyJSObject>("GetInstance");
        Debug.Log($"Hwlogin:CreateHMSManager:HMSAdsManagerObj={m_HMSLoginManagerObj}");

        HMSLoginManagerCallback = callback;
        m_HMSLoginManagerObj.Call("Login", _hmsLoginManagerCallback, true); 
    }
}
